<template>
  <div class="building-container">
    <div class="person-container">
      <LeftMenu />
      <div class="building-content">
        <el-card>
          <ManagementTitle>
            <template #title>
              楼栋详情 - {{ buildingInfo.name || '' }}栋
              <el-button size="small" @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
            </template>
          </ManagementTitle>

          <!-- 楼栋基本信息 -->
          <div class="building-info-card">
            <el-card shadow="never" class="info-card">
              <div class="building-info">
                <div class="info-details">
                  <div class="detail-row">
                    <div class="detail-item">
                      <span class="detail-label">所属小区：</span>
                      <span class="detail-value">{{ plotName }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">楼栋名称：</span>
                      <span class="detail-value">{{ buildingInfo.name }}栋</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">单元数：</span>
                      <span class="detail-value">{{ buildingInfo.unitNum }}个</span>
                    </div>
                  </div>
                  <div class="detail-row">
                    <div class="detail-item">
                      <span class="detail-label">楼层数：</span>
                      <span class="detail-value">{{ buildingInfo.floorNum }}层</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">总房源数：</span>
                      <span class="detail-value">{{ buildingInfo.totalHouses }}套</span>
                    </div>
                  </div>

                </div>
              </div>
            </el-card>
          </div>

          <!-- 操作按钮区域 -->
          <div class="building-header">
            <!-- 未选择房源时显示添加按钮 -->
            <template v-if="selectedHouses.length === 0">
              <el-button type="primary" @click="handleAddHouse">
                <el-icon><Plus /></el-icon>
                添加房源
              </el-button>
              <el-button type="success" @click="handleAddFloor">
                <el-icon><OfficeBuilding /></el-icon>
                添加楼层数
              </el-button>
              <el-button type="warning" @click="handleAddUnit">
                <el-icon><Grid /></el-icon>
                添加单元数
              </el-button>
            </template>

            <!-- 选择房源后显示批量操作按钮 -->
            <template v-else>
              <div class="batch-info">
                <span class="selected-count">已选择 {{ selectedHouses.length }} 套房源</span>
              </div>
              <el-button
                type="danger"
                @click="handleBatchDelete"
              >
                <el-icon><Delete /></el-icon>
                批量删除
              </el-button>
              <el-button @click="clearSelection">
                <el-icon><Close /></el-icon>
                取消选择
              </el-button>
            </template>
          </div>

          <!-- 选择控制区域 -->
          <div class="selection-controls">
            <el-checkbox
              v-model="selectAll"
              @change="handleSelectAll"
              :indeterminate="isIndeterminate"
            >
              全选房源
            </el-checkbox>
            <span class="selection-info">已选择 {{ selectedHouses.length }} 套房源</span>
          </div>

          <!-- 房源列表区域 -->
          <div class="house-list-container" v-loading="loading">
            <div v-if="buildingInfo.map && Object.keys(buildingInfo.map).length > 0" class="units-container">
              <!-- 单元循环 -->
              <div
                v-for="(unitData, unitNum) in buildingInfo.map"
                :key="unitNum"
                class="unit-section"
              >
                <div class="unit-title">
                  <h3>{{ unitNum }}单元</h3>
                  <el-checkbox
                    :model-value="isUnitSelected(String(unitNum))"
                    @change="(val: boolean) => handleUnitSelect(String(unitNum), val)"
                    :indeterminate="isUnitIndeterminate(String(unitNum))"
                  >
                    选择整个单元
                  </el-checkbox>
                </div>

                <!-- 楼层表格 -->
                <el-table
                  :data="getUnitFloorData(unitData, String(unitNum))"
                  border
                  class="floor-table"
                  :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
                >
                  <el-table-column label="楼层" width="80" align="center">
                    <template #default="{ row }">
                      <div class="floor-cell">
                        <el-checkbox
                          :model-value="isFloorSelected(String(unitNum), row.floorNum)"
                          @change="(val: boolean) => handleFloorSelect(String(unitNum), row.floorNum, val)"
                          :indeterminate="isFloorIndeterminate(String(unitNum), row.floorNum)"
                          size="small"
                        />
                        <span>{{ row.floorNum }}层</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="房源" min-width="200">
                    <template #default="{ row }">
                      <div class="houses-row" :style="getHousesRowStyle(row.houses.length)">
                        <div
                          v-for="house in row.houses"
                          :key="house.id"
                          class="house-cell"
                          :class="{
                            'selected': selectedHouses.includes(house.id),
                            'occupied': house.state === 1
                          }"
                          :style="getHouseCellStyle(row.houses.length)"
                          @click="handleHouseSelect(house.id)"
                        >
                          <el-checkbox
                            :model-value="selectedHouses.includes(house.id)"
                            @change="(val: boolean) => handleHouseCheckboxChange(house.id, val)"
                            @click.stop
                            size="small"
                          />
                          <span class="house-number" @click.stop="showHouseDetail(house)">{{ house.num }}</span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="该楼栋暂无房源数据">
                <el-button type="primary" @click="handleAddHouse">添加房源</el-button>
              </el-empty>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 房源详情侧滑面板 -->
    <el-drawer
      v-model="showHouseDetailDrawer"
      title="房源详情"
      direction="rtl"
      size="500px"
      :before-close="handleDrawerClose"
    >
      <div v-if="currentHouse" class="house-detail-content">
        <el-form :model="houseDetailForm" label-width="100px" ref="houseDetailFormRef">
          <el-form-item label="房号">
            <el-input v-model="houseDetailForm.num" disabled />
          </el-form-item>

          <el-form-item label="户型">
            <el-input v-model="houseDetailForm.type" placeholder="请输入户型，如：三室两厅一卫" />
          </el-form-item>

          <el-form-item label="面积(㎡)">
            <el-input-number v-model="houseDetailForm.area" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="租金(元/月)">
            <el-input-number v-model="houseDetailForm.rent" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="房屋用途">
            <el-select v-model="houseDetailForm.houseUse" style="width: 100%">
              <el-option label="住宅" :value="1" />
              <el-option label="公寓" :value="2" />
              <el-option label="办公" :value="3" />
              <el-option label="商铺" :value="4" />
              <el-option label="写字楼" :value="5" />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁类型">
            <el-select v-model="houseDetailForm.rentalType" style="width: 100%">
              <el-option label="整租" :value="1" />
              <el-option label="分租" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="房源权属">
            <el-select v-model="houseDetailForm.ownershipType" style="width: 100%">
              <el-option label="企业" :value="0" />
              <el-option label="个人" :value="1" />
              <el-option label="居间" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="装修类型">
            <el-select v-model="houseDetailForm.decoration" style="width: 100%">
              <el-option label="毛坯" :value="1" />
              <el-option label="简装" :value="2" />
              <el-option label="精装" :value="3" />
              <el-option label="豪装" :value="4" />
              <el-option label="其他" :value="5" />
            </el-select>
          </el-form-item>

          <el-form-item label="支付类型">
            <el-select v-model="houseDetailForm.payType" style="width: 100%">
              <el-option label="付一押一" :value="1" />
              <el-option label="付一押二" :value="2" />
              <el-option label="付一押三" :value="3" />
              <el-option label="付二押一" :value="4" />
              <el-option label="付三押一" :value="5" />
              <el-option label="付三押二" :value="6" />
              <el-option label="月付" :value="7" />
              <el-option label="半年付" :value="8" />
            </el-select>
          </el-form-item>

          <el-form-item label="朝向">
            <el-select v-model="houseDetailForm.orientation" style="width: 100%">
              <el-option label="东" :value="1" />
              <el-option label="南" :value="2" />
              <el-option label="西" :value="3" />
              <el-option label="北" :value="4" />
            </el-select>
          </el-form-item>

          <el-form-item label="所在楼层">
            <el-select v-model="houseDetailForm.floor" style="width: 100%">
              <el-option label="低层" :value="1" />
              <el-option label="中层" :value="2" />
              <el-option label="高层" :value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="房屋状态">
            <el-tag :type="getStatusTagType(houseDetailForm.state)">
              {{ getStatusText(houseDetailForm.state) }}
            </el-tag>
          </el-form-item>

          <el-form-item label="房屋标题">
            <el-input v-model="houseDetailForm.title" type="textarea" :rows="2" />
          </el-form-item>

          <el-form-item label="几居室">
            <el-input-number v-model="houseDetailForm.typeNum" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="区域">
            <el-select v-model="houseDetailForm.region" placeholder="请选择区域" style="width: 100%">
              <el-option
                v-for="county in allCounties"
                :key="county.id"
                :label="county.name"
                :value="county.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址">
            <el-input v-model="houseDetailForm.address" />
          </el-form-item>

          <el-form-item label="配套设施">
            <div class="facility-selection">
              <el-checkbox-group v-model="selectedFacilityIds" @change="onFacilityChange">
                <el-checkbox
                  v-for="facility in allFacilities"
                  :key="facility.id"
                  :label="facility.id"
                  class="facility-checkbox"
                >
                  {{ facility.name }}
                </el-checkbox>
              </el-checkbox-group>
              <div class="facility-preview" v-if="houseDetailForm.facilities">
                <small class="text-muted">存储格式预览：{{ houseDetailForm.facilities }}</small>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="房东要求">
            <el-input v-model="houseDetailForm.need" type="textarea" :rows="2" />
          </el-form-item>

          <el-form-item label="房源描述">
            <el-input v-model="houseDetailForm.description" type="textarea" :rows="3" />
          </el-form-item>

          <el-form-item label="房源图片">
            <div class="house-image-upload">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="houseImageList"
                :on-success="handleHouseImageSuccess"
                :on-remove="handleHouseImageRemove"
                :on-error="handleHouseImageError"
                :before-upload="beforeHouseImageUpload"
                list-type="picture-card"
                accept="image/*"
                :limit="10"
                :disabled="uploadLoading"
              >
                <el-icon v-if="!uploadLoading"><Plus /></el-icon>
                <el-icon v-else class="is-loading"><Loading /></el-icon>
              </el-upload>
              <div class="upload-tip">
                <small class="text-muted">支持jpg、png、gif等格式，最多上传10张图片，每张图片不超过5MB</small>
              </div>
              <div class="image-urls-preview" v-if="houseDetailForm.imageUrls">
                <small class="text-muted">存储格式：{{ houseDetailForm.imageUrls }}</small>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div class="drawer-footer">
          <el-button @click="handleDrawerClose">取消</el-button>
          <el-button type="primary" @click="saveHouseDetail" :loading="saveLoading">保存修改</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 移除了批量编辑对话框 -->

    <!-- 添加房源对话框 -->
    <el-dialog v-model="showAddHouseDialog" title="添加房源" width="600px" :close-on-click-modal="false">
      <el-form :model="houseForm" label-width="120px">
        <el-form-item label="楼栋" required>
          <el-input v-model="buildingInfo.name" disabled suffix-icon="栋" />
        </el-form-item>
        <el-form-item label="单元号" required>
          <el-input-number v-model="houseForm.unitNum" :min="1" :max="buildingInfo.unitNum || 1" />
        </el-form-item>
        <el-form-item label="楼层号" required>
          <el-input-number v-model="houseForm.floorNum" :min="1" :max="buildingInfo.floorNum || 1" />
        </el-form-item>
        <el-form-item label="户号" required>
          <el-input v-model="houseForm.num" placeholder="请输入户号，如：1001" />
        </el-form-item>
        <el-form-item label="房源标题">
          <el-input v-model="houseForm.title" placeholder="请输入房源标题" />
        </el-form-item>
        <el-form-item label="租金(元/月)">
          <el-input-number v-model="houseForm.rent" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="面积(平方米)">
          <el-input-number v-model="houseForm.area" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="户型">
          <el-input v-model="houseForm.type" placeholder="如：三室两厅一卫" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddHouseDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAddHouse">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加楼层对话框 -->
    <el-dialog v-model="showAddFloorDialog" title="添加楼层" width="500px" :close-on-click-modal="false">
      <el-form :model="floorForm" label-width="120px">
        <el-form-item label="楼栋" required>
          <el-input v-model="buildingInfo.name" disabled suffix-icon="栋" />
        </el-form-item>
        <el-form-item label="选择单元" required>
          <el-select v-model="floorForm.unitNum" placeholder="请选择单元" style="width: 100%">
            <el-option
              v-for="(unitData, unitNum) in buildingInfo.map"
              :key="unitNum"
              :label="`${unitNum}单元`"
              :value="parseInt(String(unitNum))"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层号">
          <el-input-number v-model="floorForm.floorNum" :min="1" placeholder="留空自动递增" />
        </el-form-item>
        <el-form-item label="每层房源数" required>
          <el-input-number v-model="floorForm.floorUserNumList" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddFloorDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAddFloor">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加单元对话框 -->
    <el-dialog v-model="showAddUnitDialog" title="添加单元" width="500px" :close-on-click-modal="false">
      <el-form :model="unitForm" label-width="120px">
        <el-form-item label="楼栋" required>
          <el-input v-model="buildingInfo.name" disabled suffix-icon="栋" />
        </el-form-item>
        <el-form-item label="单元号" required>
          <el-input-number v-model="unitForm.unitNum" :min="1" />
        </el-form-item>
        <el-form-item label="楼层数" required>
          <el-input-number v-model="unitForm.floorNum" :min="1" />
        </el-form-item>
        <el-form-item label="每层房源数" required>
          <el-input-number v-model="unitForm.floorUserNumList" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddUnitDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAddUnit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus, OfficeBuilding, Grid, Delete, Close, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import LeftMenu from '@/user/LeftMenu.vue'
import ManagementTitle from '@/components/ManagementTitle.vue'

// 路由参数
const route = useRoute()
const buildingId = ref(route.query.buildingId as string)
const buildingName = ref(route.query.buildingName as string || '')
const plotName = ref(route.query.plotName as string || '')

// 响应式数据
const loading = ref(false)
const buildingInfo = ref<any>({})
const selectedHouses = ref<string[]>([])

// 房源详情侧滑面板
const showHouseDetailDrawer = ref(false)
const currentHouse = ref<any>(null)
const saveLoading = ref(false)
const houseDetailForm = ref<any>({})
const houseDetailFormRef = ref()

// 移除了批量编辑相关变量

// 楼栋户型列表
const buildingTypes = ref<any[]>([])

// 配套设施相关
const allFacilities = ref<any[]>([])
const selectedFacilityIds = ref<number[]>([])

// 区域相关
const allCounties = ref<any[]>([])

// 图片上传相关
const uploadUrl = ref('http://127.0.0.1:8080/oss/file/upload') // 使用现有的OSS上传接口，正确路径
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + localStorage.getItem('token') // 根据实际情况调整
})
const uploadLoading = ref(false)
const houseImageList = ref<any[]>([])

// 对话框控制
const showAddHouseDialog = ref(false)
const showAddFloorDialog = ref(false)
const showAddUnitDialog = ref(false)

// 表单数据
const houseForm = ref({
  buildingId: '',
  unitNum: 1,
  floorNum: 1,
  num: '',
  title: '',
  rent: '',
  area: '',
  type: '',
  houseUse: 1,
  rentalType: 1,
  ownershipType: 1
})

const floorForm = ref({
  buildingId: '',
  unitNum: 1,
  floorNum: null,
  floorUserNumList: 1
})

const unitForm = ref({
  buildingId: '',
  unitNum: 1,
  floorNum: 1,
  floorUserNumList: 1
})

// 计算属性
const selectAll = computed({
  get: () => {
    const allHouseIds = getAllHouseIds()
    return allHouseIds.length > 0 && selectedHouses.value.length === allHouseIds.length
  },
  set: (val: boolean) => {
    if (val) {
      selectedHouses.value = getAllHouseIds()
    } else {
      selectedHouses.value = []
    }
  }
})

const isIndeterminate = computed(() => {
  const allHouseIds = getAllHouseIds()
  return selectedHouses.value.length > 0 && selectedHouses.value.length < allHouseIds.length
})

// 获取所有房源ID
const getAllHouseIds = (): string[] => {
  const ids: string[] = []
  if (buildingInfo.value.map) {
    Object.values(buildingInfo.value.map).forEach((unitData: any) => {
      Object.values(unitData).forEach((floorData: any) => {
        floorData.forEach((house: any) => {
          ids.push(house.id)
        })
      })
    })
  }
  return ids
}



// 获取单元的楼层数据（用于表格显示）
const getUnitFloorData = (unitData: any, unitNum: string) => {
  const floors: any[] = []
  Object.keys(unitData).sort((a, b) => parseInt(b) - parseInt(a)).forEach(floorNum => {
    floors.push({
      floorNum: floorNum,
      houses: unitData[floorNum]
    })
  })
  return floors
}

// 根据房源数量计算房源行样式
const getHousesRowStyle = (houseCount: number) => {
  return {
    'justify-content': houseCount <= 3 ? 'flex-start' : 'space-between'
  }
}

// 根据房源数量计算房源框样式
const getHouseCellStyle = (houseCount: number) => {
  let width = '80px'
  if (houseCount <= 2) {
    width = '100px'
  } else if (houseCount <= 4) {
    width = '80px'
  } else if (houseCount <= 6) {
    width = '70px'
  } else {
    width = '60px'
  }

  return {
    'min-width': width,
    'max-width': width,
    'flex': '0 0 auto'
  }
}

// API调用函数
const getBuildingDetails = async () => {
  if (!buildingId.value) {
    ElMessage.error('缺少楼栋ID参数')
    return
  }

  try {
    loading.value = true
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime()
    const response = await axios.get(`/rental/areabuilding/getBuildingById/${buildingId.value}?t=${timestamp}`)

    // 检查是否返回了HTML页面（代理失败）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.error('代理失败，尝试直接调用后端API')
      // 尝试直接调用后端API
      const directResponse = await axios.get(`http://127.0.0.1:8081/rental/areabuilding/getBuildingById/${buildingId.value}?t=${timestamp}`, {
        timeout: 10000,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })

      console.log('直接调用响应:', directResponse.data)

      if (directResponse.data.code === 0) {
        buildingInfo.value = directResponse.data.data || {}
        console.log('楼栋详情完整数据:', JSON.stringify(buildingInfo.value, null, 2))
        ElMessage.success('楼栋详情获取成功')
      } else {
        ElMessage.error(directResponse.data.msg || '获取楼栋详情失败')
      }
    } else if (response.data.code === 0) {
      buildingInfo.value = response.data.data || {}
      console.log('楼栋详情完整数据:', JSON.stringify(buildingInfo.value, null, 2))
      ElMessage.success('楼栋详情获取成功')
    } else {
      ElMessage.error(response.data.msg || '获取楼栋详情失败')
    }
  } catch (error) {
    console.error('获取楼栋详情失败:', error)
    ElMessage.error('获取楼栋详情失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}



// 添加房源API
const addHouse = async (houseData: any) => {
  try {
    const response = await axios.post('/rental/areaplothouse', houseData)

    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      const directResponse = await axios.post('http://127.0.0.1:8081/rental/areaplothouse', houseData, {
        headers: { 'Content-Type': 'application/json' }
      })

      if (directResponse.data.code === 0) {
        ElMessage.success('房源添加成功')
        return true
      } else {
        ElMessage.error(directResponse.data.msg || '添加房源失败')
        return false
      }
    } else if (response.data.code === 0) {
      ElMessage.success('房源添加成功')
      return true
    } else {
      ElMessage.error(response.data.msg || '添加房源失败')
      return false
    }
  } catch (error) {
    console.error('添加房源失败:', error)
    ElMessage.error('添加房源失败，请检查网络连接')
    return false
  }
}

// 添加楼层API
const addFloor = async (floorData: any) => {
  try {
    console.log('准备发送楼层数据:', JSON.stringify(floorData, null, 2))

    const response = await axios.post('/rental/areaplotfloor', floorData)

    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.log('代理失败，尝试直连')
      const directResponse = await axios.post('http://127.0.0.1:8081/rental/areaplotfloor', floorData, {
        headers: { 'Content-Type': 'application/json' }
      })

      console.log('直连响应:', directResponse.data)

      if (directResponse.data.code === 0) {
        ElMessage.success('楼层添加成功')
        return true
      } else {
        ElMessage.error(directResponse.data.msg || '添加楼层失败')
        console.error('添加楼层失败，后端返回:', directResponse.data)
        return false
      }
    } else if (response.data.code === 0) {
      ElMessage.success('楼层添加成功')
      return true
    } else {
      ElMessage.error(response.data.msg || '添加楼层失败')
      console.error('添加楼层失败，后端返回:', response.data)
      return false
    }
  } catch (error: any) {
    console.error('添加楼层失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(`添加楼层失败: ${error.response.data.msg || error.message}`)
    } else {
      ElMessage.error('添加楼层失败，请检查网络连接')
    }
    return false
  }
}

// 添加单元API
const addUnit = async (unitData: any) => {
  try {
    console.log('发送添加单元请求:', unitData)
    const response = await axios.post('/rental/areaplotunit', unitData)

    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.log('代理失败，尝试直连添加单元')
      const directResponse = await axios.post('http://127.0.0.1:8081/rental/areaplotunit', unitData, {
        headers: { 'Content-Type': 'application/json' }
      })

      console.log('直连添加单元响应:', directResponse.data)
      if (directResponse.data.code === 0) {
        ElMessage.success('单元添加成功')
        return true
      } else {
        ElMessage.error(directResponse.data.msg || '添加单元失败')
        console.error('添加单元失败:', directResponse.data)
        return false
      }
    } else if (response.data.code === 0) {
      console.log('代理添加单元成功:', response.data)
      ElMessage.success('单元添加成功')
      return true
    } else {
      console.log('代理添加单元失败:', response.data)
      ElMessage.error(response.data.msg || '添加单元失败')
      return false
    }
  } catch (error) {
    console.error('添加单元失败:', error)
    ElMessage.error('添加单元失败，请检查网络连接')
    return false
  }
}

// 批量删除房源API
const batchDeleteHouses = async () => {
  try {
    console.log('选中的房源ID (原始):', selectedHouses.value)

    // 避免精度丢失，直接使用字符串数组，让后端处理转换
    const houseIds = selectedHouses.value // 保持字符串格式
    console.log('发送给后端的房源ID:', houseIds)

    const response = await axios.delete('/rental/areaplothouse', {
      data: houseIds,
      headers: { 'Content-Type': 'application/json' }
    })

    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.log('代理失败，尝试直连删除')
      const directResponse = await axios.delete('http://127.0.0.1:8081/rental/areaplothouse', {
        data: houseIds,
        headers: { 'Content-Type': 'application/json' }
      })

      console.log('直连删除响应:', directResponse.data)

      if (directResponse.data.code === 0) {
        ElMessage.success(`成功删除 ${selectedHouses.value.length} 套房源`)
        selectedHouses.value = []
        console.log('删除成功，正在刷新楼栋详情...')
        await new Promise(resolve => setTimeout(resolve, 1000)) // 等待1秒确保删除完成
        await getBuildingDetails() // 重新获取数据
        return true
      } else {
        ElMessage.error(directResponse.data.msg || '批量删除失败')
        console.error('删除失败，后端返回:', directResponse.data)
        return false
      }
    } else if (response.data.code === 0) {
      console.log('代理删除响应:', response.data)
      ElMessage.success(`成功删除 ${selectedHouses.value.length} 套房源`)
      selectedHouses.value = []
      console.log('删除成功，正在刷新楼栋详情...')
      await new Promise(resolve => setTimeout(resolve, 1000)) // 等待1秒确保删除完成
      await getBuildingDetails() // 重新获取数据
      return true
    } else {
      ElMessage.error(response.data.msg || '批量删除失败')
      console.error('删除失败，后端返回:', response.data)
      return false
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败，请检查网络连接')
    return false
  }
}

// 事件处理函数
const goBack = () => {
  window.close()
}

// 清除选择
const clearSelection = () => {
  selectedHouses.value = []
}

// 显示房源详情
const showHouseDetail = async (house: any) => {
  currentHouse.value = house
  houseDetailForm.value = { ...house }
  showHouseDetailDrawer.value = true

  // 获取楼栋户型列表
  await getBuildingTypes()

  // 解析配套设施
  if (house.facilities) {
    selectedFacilityIds.value = await parseFacilitiesFromString(house.facilities)
  } else {
    selectedFacilityIds.value = []
  }

  // 加载房源图片列表
  updateHouseImageList()
}

// 获取楼栋户型列表
const getBuildingTypes = async () => {
  try {
    const response = await axios.get(`/rental/areaplottype/TypeidAndName/${buildingId.value}`)
    if (response.data.code === 0) {
      buildingTypes.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取户型列表失败:', error)
  }
}

// 配套设施相关方法
const loadAllFacilities = async () => {
  try {
    const response = await axios.get('/rental/housefacility/all')
    if (response.data.code === 0) {
      allFacilities.value = response.data.data || []
      console.log('配套设施列表:', allFacilities.value)
    } else {
      ElMessage.error('获取配套设施列表失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取配套设施列表失败:', error)
    ElMessage.error('获取配套设施列表失败，请检查网络连接')
  }
}

const parseFacilitiesFromString = async (facilitiesStr: string) => {
  if (!facilitiesStr) return []

  try {
    const response = await axios.post(`/rental/areaplothouse/parseFacilities?facilitiesStr=${encodeURIComponent(facilitiesStr)}`)
    if (response.data.code === 0) {
      return response.data.data || []
    }
  } catch (error) {
    console.error('解析配套设施失败:', error)
  }
  return []
}

const convertFacilitiesToString = async (facilityIds: number[]) => {
  if (!facilityIds || facilityIds.length === 0) return ''

  try {
    const response = await axios.post('/rental/areaplothouse/convertFacilities', {
      facilityIds: facilityIds
    })
    if (response.data.code === 0) {
      return response.data.data || ''
    }
  } catch (error) {
    console.error('转换配套设施失败:', error)
  }
  return ''
}

const onFacilityChange = async () => {
  const facilitiesStr = await convertFacilitiesToString(selectedFacilityIds.value)
  houseDetailForm.value.facilities = facilitiesStr
}

// 区域相关方法
const loadAllCounties = async () => {
  try {
    const response = await axios.get('/rental/areacounty/getAllCounty')
    if (response.data.code === 0) {
      allCounties.value = response.data.data || []
      console.log('区域列表:', allCounties.value)
    } else {
      ElMessage.error('获取区域列表失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取区域列表失败:', error)
    ElMessage.error('获取区域列表失败，请检查网络连接')
  }
}

// 图片上传相关方法
const parseImageUrls = (imageUrlsStr: string): string[] => {
  if (!imageUrlsStr) return []
  return imageUrlsStr.split(',').filter(url => url.trim())
}

const formatImageUrls = (urls: string[]): string => {
  return urls.filter(url => url.trim()).join(',')
}

const updateHouseImageList = () => {
  const urls = parseImageUrls(houseDetailForm.value.imageUrls || '')
  houseImageList.value = urls.map((url, index) => ({
    uid: index,
    name: `image-${index + 1}`,
    status: 'done',
    url: url
  }))
}

const beforeHouseImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

const handleHouseImageSuccess = (response: any, file: any) => {
  uploadLoading.value = false
  if (response.code === 0) {
    const currentUrls = parseImageUrls(houseDetailForm.value.imageUrls || '')
    // OSS接口返回的是UploadDTO对象，包含url字段
    currentUrls.push(response.data.url)
    houseDetailForm.value.imageUrls = formatImageUrls(currentUrls)
    updateHouseImageList()
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败：' + response.msg)
  }
}

const handleHouseImageRemove = (file: any) => {
  const currentUrls = parseImageUrls(houseDetailForm.value.imageUrls || '')
  const filteredUrls = currentUrls.filter(url => url !== file.url)
  houseDetailForm.value.imageUrls = formatImageUrls(filteredUrls)
  updateHouseImageList()
}

const handleHouseImageError = (error: any) => {
  uploadLoading.value = false
  ElMessage.error('图片上传失败，请重试')
  console.error('图片上传错误:', error)
}

// 关闭侧滑面板
const handleDrawerClose = () => {
  showHouseDetailDrawer.value = false
  currentHouse.value = null
  houseDetailForm.value = {}
  selectedFacilityIds.value = []
  houseImageList.value = []
}

// 保存房源详情
const saveHouseDetail = async () => {
  try {
    saveLoading.value = true
    const response = await axios.put(`/rental/areaplothouse/${currentHouse.value.id}`, houseDetailForm.value)

    if (response.data.code === 0) {
      ElMessage.success('房源信息更新成功')
      handleDrawerClose()
      await getBuildingDetails() // 刷新数据
    } else {
      ElMessage.error(response.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('保存房源详情失败:', error)
    ElMessage.error('保存失败，请检查网络连接')
  } finally {
    saveLoading.value = false
  }
}

// 移除了批量编辑相关函数

// 获取状态标签类型
const getStatusTagType = (state: number) => {
  switch (state) {
    case 0: return 'info'    // 空闲
    case 1: return 'success' // 已租
    case 2: return 'danger'  // 已删除
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (state: number) => {
  switch (state) {
    case 0: return '空闲'
    case 1: return '已租'
    case 2: return '已删除'
    default: return '未知'
  }
}

const handleSelectAll = (val: boolean) => {
  selectAll.value = val
}

const handleHouseSelect = (houseId: string) => {
  const index = selectedHouses.value.indexOf(houseId)
  if (index > -1) {
    selectedHouses.value.splice(index, 1)
  } else {
    selectedHouses.value.push(houseId)
  }
}

const handleHouseCheckboxChange = (houseId: string, val: boolean) => {
  if (val) {
    if (!selectedHouses.value.includes(houseId)) {
      selectedHouses.value.push(houseId)
    }
  } else {
    const index = selectedHouses.value.indexOf(houseId)
    if (index > -1) {
      selectedHouses.value.splice(index, 1)
    }
  }
}

// 单元选择相关
const isUnitSelected = (unitNum: string): boolean => {
  const unitHouseIds = getUnitHouseIds(unitNum)
  return unitHouseIds.length > 0 && unitHouseIds.every(id => selectedHouses.value.includes(id))
}

const isUnitIndeterminate = (unitNum: string): boolean => {
  const unitHouseIds = getUnitHouseIds(unitNum)
  const selectedCount = unitHouseIds.filter(id => selectedHouses.value.includes(id)).length
  return selectedCount > 0 && selectedCount < unitHouseIds.length
}

const getUnitHouseIds = (unitNum: string): string[] => {
  const ids: string[] = []
  if (buildingInfo.value.map && buildingInfo.value.map[unitNum]) {
    Object.values(buildingInfo.value.map[unitNum]).forEach((floorData: any) => {
      floorData.forEach((house: any) => {
        ids.push(house.id)
      })
    })
  }
  return ids
}

const handleUnitSelect = (unitNum: string, val: boolean) => {
  const unitHouseIds = getUnitHouseIds(unitNum)
  if (val) {
    unitHouseIds.forEach(id => {
      if (!selectedHouses.value.includes(id)) {
        selectedHouses.value.push(id)
      }
    })
  } else {
    selectedHouses.value = selectedHouses.value.filter(id => !unitHouseIds.includes(id))
  }
}

// 楼层选择相关
const isFloorSelected = (unitNum: string, floorNum: string): boolean => {
  const floorHouseIds = getFloorHouseIds(unitNum, floorNum)
  return floorHouseIds.length > 0 && floorHouseIds.every(id => selectedHouses.value.includes(id))
}

const isFloorIndeterminate = (unitNum: string, floorNum: string): boolean => {
  const floorHouseIds = getFloorHouseIds(unitNum, floorNum)
  const selectedCount = floorHouseIds.filter(id => selectedHouses.value.includes(id)).length
  return selectedCount > 0 && selectedCount < floorHouseIds.length
}

const getFloorHouseIds = (unitNum: string, floorNum: string): string[] => {
  const ids: string[] = []
  if (buildingInfo.value.map && buildingInfo.value.map[unitNum] && buildingInfo.value.map[unitNum][floorNum]) {
    buildingInfo.value.map[unitNum][floorNum].forEach((house: any) => {
      ids.push(house.id)
    })
  }
  return ids
}

const handleFloorSelect = (unitNum: string, floorNum: string, val: boolean) => {
  const floorHouseIds = getFloorHouseIds(unitNum, floorNum)
  if (val) {
    floorHouseIds.forEach(id => {
      if (!selectedHouses.value.includes(id)) {
        selectedHouses.value.push(id)
      }
    })
  } else {
    selectedHouses.value = selectedHouses.value.filter(id => !floorHouseIds.includes(id))
  }
}

// 操作按钮处理函数
const handleAddHouse = () => {
  showAddHouseDialog.value = true
}

const handleAddFloor = () => {
  showAddFloorDialog.value = true
}

const handleAddUnit = () => {
  showAddUnitDialog.value = true
}

const handleBatchDelete = async () => {
  if (selectedHouses.value.length === 0) {
    ElMessage.warning('请先选择要删除的房源')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHouses.value.length} 套房源吗？删除后无法恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await batchDeleteHouses()
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 对话框确认处理函数
const handleConfirmAddHouse = async () => {
  if (!houseForm.value.num) {
    ElMessage.warning('请输入户号')
    return
  }

  const houseData = {
    buildingId: buildingId.value, // 直接使用字符串避免精度丢失
    unitNum: houseForm.value.unitNum,
    floorNum: houseForm.value.floorNum,
    num: parseInt(houseForm.value.num),
    title: houseForm.value.title,
    rent: houseForm.value.rent,
    area: houseForm.value.area,
    type: houseForm.value.type,
    houseUse: houseForm.value.houseUse,
    rentalType: houseForm.value.rentalType,
    ownershipType: houseForm.value.ownershipType
  }

  console.log('发送的房源数据:', houseData)

  const success = await addHouse(houseData)
  if (success) {
    showAddHouseDialog.value = false
    resetHouseForm()
    console.log('房源添加成功，正在刷新楼栋详情...')
    await new Promise(resolve => setTimeout(resolve, 500)) // 等待确保操作完成
    await getBuildingDetails() // 重新获取数据
  }
}

const handleConfirmAddFloor = async () => {
  if (!floorForm.value.unitNum) {
    ElMessage.warning('请选择单元')
    return
  }

  console.log('选择的单元号:', floorForm.value.unitNum)
  console.log('楼栋ID (原始):', buildingId.value)
  console.log('楼栋ID (类型):', typeof buildingId.value)

  // JavaScript精度问题：直接使用字符串，让后端处理转换
  console.log('Number.MAX_SAFE_INTEGER:', Number.MAX_SAFE_INTEGER)
  console.log('楼栋ID是否超出安全范围:', Number(buildingId.value) > Number.MAX_SAFE_INTEGER)

  const floorData = {
    buildingId: buildingId.value, // 直接使用字符串，避免精度丢失
    unitNum: floorForm.value.unitNum,
    floorNum: floorForm.value.floorNum,
    floorUserNumList: floorForm.value.floorUserNumList
  }

  console.log('发送的楼层数据:', floorData)

  const success = await addFloor(floorData)
  if (success) {
    showAddFloorDialog.value = false
    resetFloorForm()
    console.log('添加楼层成功，正在重新获取楼栋详情...')
    // 等待一小段时间确保数据库操作完成
    await new Promise(resolve => setTimeout(resolve, 500))
    await getBuildingDetails() // 重新获取数据
    console.log('楼栋详情刷新完成')
  }
}

const handleConfirmAddUnit = async () => {
  console.log('楼栋ID (原始):', buildingId.value)
  console.log('直接使用字符串避免精度丢失')

  const unitData = {
    buildingId: buildingId.value, // 直接使用字符串
    unitNum: unitForm.value.unitNum,
    floorNum: unitForm.value.floorNum,
    floorUserNumList: unitForm.value.floorUserNumList
  }

  const success = await addUnit(unitData)
  if (success) {
    showAddUnitDialog.value = false
    resetUnitForm()
    console.log('添加单元成功，正在重新获取楼栋详情...')
    // 等待一小段时间确保数据库操作完成
    await new Promise(resolve => setTimeout(resolve, 500))
    await getBuildingDetails() // 重新获取数据
    console.log('楼栋详情刷新完成')
  }
}

// 表单重置函数
const resetHouseForm = () => {
  houseForm.value = {
    buildingId: buildingId.value,
    unitNum: 1,
    floorNum: 1,
    num: '',
    title: '',
    rent: '',
    area: '',
    type: '',
    houseUse: 1,
    rentalType: 1,
    ownershipType: 1
  }
}

const resetFloorForm = () => {
  floorForm.value = {
    buildingId: buildingId.value,
    unitNum: 1,
    floorNum: null,
    floorUserNumList: 1
  }
}

const resetUnitForm = () => {
  unitForm.value = {
    buildingId: buildingId.value,
    unitNum: 1,
    floorNum: 1,
    floorUserNumList: 1
  }
}



// 初始化
onMounted(() => {
  if (!buildingId.value) {
    ElMessage.error('缺少楼栋ID参数')
    return
  }

  // 初始化表单默认值
  houseForm.value.buildingId = buildingId.value
  unitForm.value.buildingId = buildingId.value
  floorForm.value.buildingId = buildingId.value

  getBuildingDetails()
  loadAllFacilities()
  loadAllCounties()
  // 不再需要单独获取单元列表，直接从楼栋数据中获取
})
</script>

<style scoped>
.building-container {
  display: flex;
  flex-direction: column;
}

.person-container {
  max-width: 1290px;
  width: 100%;
  margin: 20px auto;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  box-sizing: border-box;
}

.building-content {
  margin-left: 10px;
  flex: 1 1 0;
  min-width: 0;
  width: 100%;
  max-width: 100%;
}

.building-info-card {
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.building-info {
  padding: 0;
}

.info-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.detail-item.full-width {
  min-width: 100%;
}

.detail-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  white-space: nowrap;
}

.detail-value {
  color: #303133;
  font-weight: 600;
}

.building-header {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.batch-info {
  display: flex;
  align-items: center;
  margin-right: 16px;
}

.selected-count {
  background: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.selection-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.selection-info {
  color: #606266;
  font-size: 14px;
}

.house-list-container {
  background-color: #fff;
  border-radius: 6px;
  padding: 20px;
}

.units-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.unit-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  flex: 1 1 calc(50% - 10px);
  min-width: 400px;
}

.unit-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.unit-title h3 {
  margin: 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.floor-table {
  width: 100%;
}

.floor-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.houses-row {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  padding: 8px 0;
  justify-content: flex-start;
}

.house-cell {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  flex: 1 1 auto;
  min-width: 60px;
  max-width: 120px;
  justify-content: center;
}

.house-cell:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.house-cell.selected {
  border-color: #409eff;
  background-color: #409eff;
  color: #fff;
}

.house-cell.occupied {
  border-color: #f56c6c;
  background-color: #fef0f0;
  color: #f56c6c;
}

.house-cell.selected.occupied {
  border-color: #f56c6c;
  background-color: #f56c6c;
  color: #fff;
}

.house-number {
  font-weight: 500;
  cursor: pointer;
  transition: color 0.3s;
}

.house-number:hover {
  color: #40a9ff;
  text-decoration: underline;
}

/* 房源详情侧滑面板样式 */
.house-detail-content {
  padding: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

/* 移除了批量编辑对话框样式 */

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 响应式设计 */
@media (max-width: 900px) {
  .person-container {
    flex-direction: column;
    align-items: stretch;
    padding: 0 4px;
  }

  .building-content {
    margin-left: 0;
    width: 100%;
    max-width: 100%;
  }

  .units-container {
    flex-direction: column;
  }

  .unit-section {
    flex: 1 1 100%;
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .detail-row {
    flex-direction: column;
    gap: 12px;
  }

  .detail-item {
    min-width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .building-header {
    flex-direction: column;
  }

  .selection-controls {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .unit-title {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .houses-row {
    justify-content: flex-start !important;
  }
}

/* 配套设施样式 */
.facility-selection {
  width: 100%;
}

.facility-checkbox {
  display: inline-block;
  margin: 4px 8px 4px 0;
  white-space: nowrap;
}

:deep(.facility-checkbox .el-checkbox__label) {
  font-size: 13px;
  padding-left: 6px;
}

.facility-preview {
  margin-top: 8px;
  padding: 6px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

/* 图片上传样式 */
.house-image-upload {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
}

.image-urls-preview {
  margin-top: 8px;
  padding: 6px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  word-break: break-all;
}

:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
